package com.smartview.jboss.spring.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.hibernate.ejb.EntityManagerFactoryImpl;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.smartview.jboss.spring.dto.LoginDTO;
import com.smartview.jboss.spring.dto.UserDTO;
import com.smartview.jboss.spring.dto.WeatherDTO;

@Repository
@Transactional
public class LoginDao {
	// We need to use the entity manager factory bean provided by spring framework
	@PersistenceContext
	private EntityManager em;
	

	
	@Transactional(readOnly = true)
	public LoginDTO getAccount(String id) {
		// Here, I am going to the DB to grab the weather info
		// make it as an instance of weather,and then return it to you.
		return em.find(LoginDTO.class, id);
	}
	
/*	public void saveWeather(WeatherDTO weather) {
		// You give me the weather information, and I will save it to the DB
		em.persist(weather);
	}
*/
/*	@Transactional(readOnly = true)
	public UserDTO getUserData() {
		@SuppressWarnings("unchecked")
		UserDTO dto = (UserDTO)em.createQuery("select data from UserDTO data").getResultList().get(0);
		return dto;
	}*/
	
/*	@Transactional(readOnly = true)
	public UserDTO getCheckUser(String id){
		@SuppressWarnings("unchecked")
		UserDTO dto = (UserDTO)em.createQuery("select data from UserDTO data where id= :id").setParameter("id", id).getResultList().get(0);
		return dto;
	}*/
	
	public void deleteService(String id, String service_code){
		@SuppressWarnings("unchecked")
		String hql = "delete from LoginDTO where id = :id and service_code = :service_code ";
        em.createQuery(hql).setParameter("id", id).setParameter("service_code", service_code).executeUpdate();
	}
	
	public void saveAccount(LoginDTO dto) {
		// You give me the weather information, and I will save it to the DB
		
		em.persist(dto);
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<LoginDTO> getServiceAccounts(String id){
		StringBuffer sb = new StringBuffer();
		
		sb.append(" select dto")
		  .append(" from LoginDTO dto ")
		  .append(" where id = :id ");
		
		Query q = em.createQuery(sb.toString())
				.setParameter("id", id);
		
		List<LoginDTO> l = new ArrayList<LoginDTO>();
		
	    for (LoginDTO dto : (List<LoginDTO>) q.getResultList()) {
	    	l.add(dto);
	    }
	    
		return l;
	}
}
